<?php

/**
 * @file 将 cron 表中已经执行完成的记录，迁移到 cron_history 表，以提高 cron 表的读写效率
 */

___cron_history();

function ___cron_history() {

  // 在 cron_history 正常执行的情况下，cron 数据量较小，读取全表比使用 group by 或 distinct 效率更高
  if ($fetch = db_query('SELECT * FROM {cron} ORDER BY cid DESC')) {
    $data = array();
    foreach ($fetch as $o) {
      $data[$o->type][] = $o;
    }

    // 状态为 3，表示由人工或系统终止运行的记录，若 10 分钟未更新，则迁移
    $time = time()-600;

    foreach ($data as $v) {
      // 每个类别保留最新一条，并删除已经成功执行的任务
      $is_first = 1;
      foreach ($v as $o) {
        if ($o->status == 2 || ($o->status == 3 && $o->updated < $time)) {
          if (empty($is_first)) {
            if (db_exec('INSERT INTO {cron_history} SET type = ?, status = ?, data = ?, 
              date = ?, updated = ?, created = ?, weight = ?',
              array($o->type, $o->status, $o->data, $o->date, $o->updated, $o->created, $o->weight))) {
              $cids[] = $o->cid;
            }
          }
        }
        $is_first = 0;
      }
    }

    if (!empty($cids)) {
      db_exec('DELETE FROM {cron} WHERE cid IN (:cids)', array(':cids' => $cids));
      dd_log('cron_info', t('system', '迁移 !count 条历史任务，耗时 !time 秒', array(
        '!count' => count($cids),
        '!time' => round(microtime(true)-DIDA_START_TIME, 4)
      )));
    }
  }
}
